# coding:utf-8


import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QMainWindow


class Calc(QMainWindow):
  def __init__(self):
    QMainWindow.__init__(self)
    self.x = None
    self.y = None
    self.result = None
    self.operator = None
    self.equal = None

    uic.loadUi("calc.ui", self)
    btns = [
        self.pushButton0,
        self.pushButton1,
        self.pushButton2,
        self.pushButton3,
        self.pushButton4,
        self.pushButton5,
        self.pushButton6,
        self.pushButton7,
        self.pushButton8,
        self.pushButton9,
        self.pushButton_add,
        self.pushButton_mul,
        self.pushButton_sub,
        self.pushButton_equal,
        self.pushButton_clear,
        self.pushButton_div,
        self.pushButton_dot
    ]
    #map(lambda but:but.clicked.connect(self.click_on_button),btns)
    for btn in btns:
      btn.clicked.connect(self.click_on_button)

  def calculate(self):
    """
    如果x、y、opreater不为空，计算结果

    """
    if self.x and self.y and self.operator:
      self.x = self.result = str(
          eval("%s%s%s" % (self.x, self.operator, self.y)))
      self.y = None
      self.text_result.setText(self.result)

  def click_on_button(self):
    value = self.sender().text()

    if value in "0123456789.":
      print "您点击的数字是：", value
      if self.operator is not None:

        if self.y is not None:
          self.y += value
        else:
          self.y = value
        self.text_result.setText(self.y)

      else:

        if self.x is not None:
          self.x += value
        else:
          self.x = value
        self.text_result.setText(self.x)

      # 如果点击的是数字的话，保存到x或追加到x

    elif value in "+-*/":
      self.operator = value
      if self.x is None:
        self.x = 0
      if self.x and self.y and self.operator:
        self.calculate()

    elif value == "=":
      if self.x and self.y and self.operator:
        self.calculate()

    else:
      self.clear()

  def clear(self):
    self.x = None
    self.y = None
    self.result = None
    self.operator = None
    self.text_result.setText("")


if __name__ == '__main__':
  app = QApplication(sys.argv)
  calc = Calc()
  calc.show()

  app.exec_()
